const { TOKEN_PREFIX, USER_LIST_SORT_SET } = require('../src/consts/system')
require('../src/config/default')
const { createRedisClient, getUserDB } = require('./utils/redis')
const conn = createRedisClient()
let db = getUserDB()

!(async () => {
  try {
    await conn.connect()
    console.log('Redis client connected successfully')

    // 开启过期通知
    await conn.configSet('notify-keyspace-events', 'Ex')
    console.log('notify-keyspace-events configured to Ex')

    // 订阅过期事件 __keyevent@0__:expired 表示 第 0 个数据库的过期事件
    await conn.subscribe(`__keyevent@${db}__:expired`, async (expiredKey) => {
      console.log(`[过期事件] Key "${expiredKey}" 已过期`)
      // 移除在线人员数据
      if (expiredKey.startsWith(TOKEN_PREFIX)) {
        const phone = expiredKey.split(':')[1]
        console.log(phone, '<<< phone 过期')

        try {
          const rmConn = createRedisClient()
          await rmConn.connect()
          // 移除在线人员数据
          await rmConn.zRem(USER_LIST_SORT_SET, phone)
          await rmConn.close()
          console.log(
            `Successfully removed ${phone} from ${USER_LIST_SORT_SET}`
          )
        } catch (error) {
          console.error(
            `Error removing ${phone} from ${USER_LIST_SORT_SET}:`,
            error
          )
        }
      }
    })

    process.on('SIGINT', async () => {
      console.log('Received SIGINT, closing Redis connection...')
      await conn.close()
      process.exit()
    })

    console.log('Redis 过期事件监听已启动')
  } catch (error) {
    console.error('Error initializing Redis expiration listener:', error)
    process.exit(1)
  }
})()
